<!DOCTYPE html>
<html class="client-nojs vector-feature-night-mode-disabled vector-feature-language-in-header-enabled vector-feature-language-in-main-page-header-disabled vector-feature-page-tools-pinned-disabled vector-feature-toc-pinned-clientpref-1 vector-feature-main-menu-pinned-disabled vector-feature-limited-width-clientpref-1 vector-feature-limited-width-content-enabled vector-feature-custom-font-size-clientpref-1 vector-feature-appearance-pinned-clientpref-1 vector-sticky-header-enabled" lang="en" dir="ltr"><head>
<meta charset="UTF-8">
<title>Command–query separation</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="canonical" href="https://en.wikipedia.org/wiki/Command%E2%80%93query_separation"> <link href="./mw/ext.cite.styles.css" rel="stylesheet" type="text/css">
<link href="./mw/ext.pygments.css" rel="stylesheet" type="text/css">
<link href="./mw/skins.vector.icons.css" rel="stylesheet" type="text/css">
<link href="./mw/skins.vector.search.codex.styles.css" rel="stylesheet" type="text/css">
<link href="./mw/skins.vector.styles.css" rel="stylesheet" type="text/css">
<link href="./mw/user.styles.css" rel="stylesheet" type="text/css">
<meta name="ResourceLoaderDynamicStyles" content="">
<link rel="stylesheet" type="text/css" href="./mw/site.styles.css">
<link rel="stylesheet" type="text/css" href="./mw/noscript.css">
<link rel="stylesheet" type="text/css" href="./footer.css">
<link rel="stylesheet" type="text/css" href="./vector-2022.css">
</head>
<body class="skin--responsive skin-vector skin-vector-search-vue mediawiki ltr sitedir-ltr mw-hide-empty-elt ns-0 ns-subject page-Command–query_separation rootpage-Command–query_separation skin-vector-2022 action-view">
<div class="mw-page-container">
<div class="mw-page-container-inner">
<div class="mw-content-container">
<main id="content" class="mw-body">
<header class="mw-body-header vector-page-titlebar">
<h1 id="firstHeading" class="firstHeading mw-first-heading">
<span id="openzim-page-title" class="mw-page-title-main"><span class="mw-page-title-main">Command–query separation</span></span>
</h1>
</header>
<a id="top"></a>
<div id="bodyContent" class="vector-body ve-init-mw-desktopArticleTarget-targetContainer" aria-labelledby="firstHeading" data-mw-ve-target-container="">
<div id="mw-content-text" class="mw-body-content mw-content-ltr" lang="en" dir="ltr"><div class="mw-content-ltr mw-parser-output" lang="en" dir="ltr">
<style data-mw-deduplicate="TemplateStyles:r1251242444">
/* start https://en.wikipedia.org/ */
.mw-parser-output .ambox{border:1px solid #a2a9b1;border-left:10px solid #36c;background-color:#fbfbfb;box-sizing:border-box}.mw-parser-output .ambox+link+.ambox,.mw-parser-output .ambox+link+style+.ambox,.mw-parser-output .ambox+link+link+.ambox,.mw-parser-output .ambox+.mw-empty-elt+link+.ambox,.mw-parser-output .ambox+.mw-empty-elt+link+style+.ambox,.mw-parser-output .ambox+.mw-empty-elt+link+link+.ambox{margin-top:-1px}html body.mediawiki .mw-parser-output .ambox.mbox-small-left{margin:4px 1em 4px 0;overflow:hidden;width:238px;border-collapse:collapse;font-size:88%;line-height:1.25em}.mw-parser-output .ambox-speedy{border-left:10px solid #b32424;background-color:#fee7e6}.mw-parser-output .ambox-delete{border-left:10px solid #b32424}.mw-parser-output .ambox-content{border-left:10px solid #f28500}.mw-parser-output .ambox-style{border-left:10px solid #fc3}.mw-parser-output .ambox-move{border-left:10px solid #9932cc}.mw-parser-output .ambox-protection{border-left:10px solid #a2a9b1}.mw-parser-output .ambox .mbox-text{border:none;padding:0.25em 0.5em;width:100%}.mw-parser-output .ambox .mbox-image{border:none;padding:2px 0 2px 0.5em;text-align:center}.mw-parser-output .ambox .mbox-imageright{border:none;padding:2px 0.5em 2px 0;text-align:center}.mw-parser-output .ambox .mbox-empty-cell{border:none;padding:0;width:1px}.mw-parser-output .ambox .mbox-image-div{width:52px}@media(min-width:720px){.mw-parser-output .ambox{margin:0 10%}}@media print{body.ns-0 .mw-parser-output .ambox{display:none!important}}
/* end https://en.wikipedia.org/ */
</style>
<p><b>Command-query separation</b> (<b>CQS</b>) is a principle of <a href="Imperative_programming" title="Imperative programming">imperative</a> <a href="Computer_programming" title="Computer programming">computer programming</a>. It was devised by <a href="Bertrand_Meyer" title="Bertrand Meyer">Bertrand Meyer</a> as part of his pioneering work on the <a href="Eiffel_(programming_language)" title="Eiffel (programming language)">Eiffel programming language</a>.
</p><p>It states that every <a href="Method_(computer_science)" class="mw-redirect" title="Method (computer science)">method</a> should either be a <i>command</i> that performs an action, or a <i>query</i> that returns data to the caller, but not both. In other words, <i>asking a question should not change the answer</i>.<sup id="cite_ref-1" class="reference"><a href="#cite_note-1"><span class="cite-bracket">[</span>1<span class="cite-bracket">]</span></a></sup> More formally, methods should return a value only if they are <a href="Referential_transparency" title="Referential transparency">referentially transparent</a> and hence possess no <a href="Side_effect_(computer_science)" title="Side effect (computer science)">side effects</a>.
</p>
<meta property="mw:PageProp/toc">
<div class="mw-heading mw-heading2"><h2 id="Connection_with_design_by_contract">Connection with design by contract</h2></div>
<p>Command-query separation is particularly well suited to a <a href="Design_by_contract" title="Design by contract">design by contract</a> (DbC) methodology, in which the design of a <a href="Computer_program" title="Computer program">program</a> is expressed as <a href="Assertion_(software_development)" title="Assertion (software development)">assertions</a> embedded in the <a href="Source_code" title="Source code">source code</a>, describing the <a href="State_(computer_science)" title="State (computer science)">state</a> of the program at certain critical times. In DbC, assertions are considered design annotations—not program logic—and as such, their execution should not affect the program state. CQS is beneficial to DbC because any value-returning method (any query) can be called by any assertion without fear of modifying program state.
</p><p>In theoretical terms, this establishes a measure of sanity, whereby one can reason about a program's state without simultaneously modifying that state. In practical terms, CQS allows all assertion checks to be bypassed in a working system to improve its performance without inadvertently modifying its behaviour. CQS may also prevent the occurrence of certain kinds of <a href="Heisenbug" title="Heisenbug">heisenbugs</a>.
</p>
<div class="mw-heading mw-heading2"><h2 id="Broader_impact_on_software_engineering">Broader impact on software engineering</h2></div>
<p>Even beyond the connection with design by contract, CQS is considered by its adherents to have a simplifying effect on a program, making its states (via queries) and state changes (via commands) more comprehensible.
</p><p>CQS is well-suited to the <a href="Object-oriented_programming" title="Object-oriented programming">object-oriented</a> methodology, but can also be applied outside of object-oriented programming. Since the separation of side effects and return values is not inherently object-oriented, CQS can be profitably applied to any programming paradigm that requires reasoning about side effects.
</p>
<div class="mw-heading mw-heading2"><h2 id="Command_Query_Responsibility_Segregation">Command Query Responsibility Segregation</h2></div>
<p><a href="Command_Query_Responsibility_Segregation" title="Command Query Responsibility Segregation"><b>Command query responsibility segregation</b> (<b>CQRS</b>)</a> generalises CQS to services, at the architectures level: it applies the CQS principle by using separate <i>Query</i> and <i>Command</i> interfaces and usually data models to <i>retrieve</i> and <i>modify</i> data, respectively.<sup id="cite_ref-2" class="reference"><a href="#cite_note-2"><span class="cite-bracket">[</span>2<span class="cite-bracket">]</span></a></sup><sup id="cite_ref-FowlerCQRS_3-0" class="reference"><a href="#cite_note-FowlerCQRS-3"><span class="cite-bracket">[</span>3<span class="cite-bracket">]</span></a></sup>
</p>
<div class="mw-heading mw-heading2"><h2 id="Other_architectural_patterns">Other architectural patterns</h2></div>
<ul><li>As we move away from a single representation that we interact with via <a href="CRUD" class="mw-redirect" title="CRUD">CRUD</a>, we can easily move to a task-based UI.</li>
<li>CQRS fits well with event-based programming models. It's common to see a CQRS system split into separate services communicating with Event Collaboration. This allows these services to easily take advantage of <a href="Event_Driven_Architecture" class="mw-redirect" title="Event Driven Architecture">Event Driven Architecture</a>.</li>
<li>Having separate models raises questions about how hard it is to keep those models consistent, which raises the likelihood of using eventual consistency.</li>
<li>For many domains, much of the logic required is needed when you're updating, so it may make sense to use Eager Read Derivation to simplify your query-side models.</li>
<li>If the write model generates events for all updates, you can structure read models as Event Posters, allowing them to be Memory Images and thus avoiding a lot of database interactions.</li>
<li>CQRS is suited to complex domains, the kind that also benefits from <a href="Domain-driven_design" title="Domain-driven design">Domain-Driven Design</a>.<sup id="cite_ref-FowlerCQRS_3-1" class="reference"><a href="#cite_note-FowlerCQRS-3"><span class="cite-bracket">[</span>3<span class="cite-bracket">]</span></a></sup></li></ul>
<div class="mw-heading mw-heading2"><h2 id="Limitations">Limitations</h2></div>
<p>CQS can introduce complexities for implementing <a href="Reentrant_(subroutine)" class="mw-redirect" title="Reentrant (subroutine)">reentrant</a> and <a href="Multithreading_(software)" class="mw-redirect" title="Multithreading (software)">multithreaded</a> software correctly. This usually occurs when a non-thread-safe pattern is used to implement the command-query separation.
</p><p>Here is a simple example that does not follow CQS, but is useful for multi-threaded software because it solves the complexity of locking for all other parts of the program, but by doing so it doesn't follow CQS because the function both mutates state and returns it:
</p>
<div class="mw-highlight mw-highlight-lang-java mw-content-ltr" dir="ltr"><pre><span class="kd">private</span><span class="w"> </span><span class="kt">int</span><span class="w"> </span><span class="n">x</span><span class="p">;</span>
<span class="kd">public</span><span class="w"> </span><span class="kt">int</span><span class="w"> </span><span class="nf">incrementAndReturnX</span><span class="p">()</span><span class="w"> </span><span class="p">{</span>
<span class="w"> </span><span class="n">lock</span><span class="w"> </span><span class="n">x</span><span class="p">;</span><span class="w"> </span><span class="c1">// by some mechanism</span>
<span class="w"> </span><span class="n">x</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">x</span><span class="w"> </span><span class="o">+</span><span class="w"> </span><span class="mi">1</span><span class="p">;</span>
<span class="w"> </span><span class="kt">int</span><span class="w"> </span><span class="n">x_copy</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">x</span><span class="p">;</span>
<span class="w"> </span><span class="n">unlock</span><span class="w"> </span><span class="n">x</span><span class="p">;</span><span class="w"> </span><span class="c1">// by some mechanism</span>
<span class="w"> </span><span class="k">return</span><span class="w"> </span><span class="n">x_copy</span><span class="p">;</span>
<span class="p">}</span>
</pre></div>
<p>Here is a CQS-compliant version. Note that it is safely usable only in single-threaded applications. In a multithreaded program, there is a race condition in the caller, between where <code>increment()</code> and <code>value()</code> would be called:
</p>
<div class="mw-highlight mw-highlight-lang-java mw-content-ltr" dir="ltr"><pre><span class="kd">private</span><span class="w"> </span><span class="kt">int</span><span class="w"> </span><span class="n">x</span><span class="p">;</span>
<span class="kd">public</span><span class="w"> </span><span class="kt">int</span><span class="w"> </span><span class="nf">value</span><span class="p">()</span><span class="w"> </span><span class="p">{</span>
<span class="w"> </span><span class="k">return</span><span class="w"> </span><span class="n">x</span><span class="p">;</span>
<span class="p">}</span>
<span class="kt">void</span><span class="w"> </span><span class="nf">increment</span><span class="p">()</span><span class="w"> </span><span class="p">{</span>
<span class="w"> </span><span class="n">x</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">x</span><span class="w"> </span><span class="o">+</span><span class="w"> </span><span class="mi">1</span><span class="p">;</span>
<span class="p">}</span>
</pre></div>
<p>Even in single-threaded programs, it is sometimes arguably significantly more convenient to have a method that is a combined query and command. <a href="Martin_Fowler_(software_engineer)" title="Martin Fowler (software engineer)">Martin Fowler</a> cites the <code>pop()</code> method of a <a href="Stack_(abstract_data_type)" title="Stack (abstract data type)">stack</a> as an example.<sup id="cite_ref-4" class="reference"><a href="#cite_note-4"><span class="cite-bracket">[</span>4<span class="cite-bracket">]</span></a></sup>
</p>
<div class="mw-heading mw-heading2"><h2 id="See_also">See also</h2></div>
<ul><li><a href="Idempotence#Computer_science_meaning" title="Idempotence">Idempotence</a></li>
<li><a href="Domain-driven_design" title="Domain-driven design">Domain-driven design</a></li>
<li><a href="Create%2C_read%2C_update_and_delete" title="Create, read, update and delete">Create, read, update and delete</a> (CRUD)</li></ul>
<div class="mw-heading mw-heading2"><h2 id="References">References</h2></div>
<style data-mw-deduplicate="TemplateStyles:r1239543626">
/* start https://en.wikipedia.org/ */
.mw-parser-output .reflist{margin-bottom:0.5em;list-style-type:decimal}@media screen{.mw-parser-output .reflist{font-size:90%}}.mw-parser-output .reflist .references{font-size:100%;margin-bottom:0;list-style-type:inherit}.mw-parser-output .reflist-columns-2{column-width:30em}.mw-parser-output .reflist-columns-3{column-width:25em}.mw-parser-output .reflist-columns{margin-top:0.3em}.mw-parser-output .reflist-columns ol{margin-top:0}.mw-parser-output .reflist-columns li{page-break-inside:avoid;break-inside:avoid-column}.mw-parser-output .reflist-upper-alpha{list-style-type:upper-alpha}.mw-parser-output .reflist-upper-roman{list-style-type:upper-roman}.mw-parser-output .reflist-lower-alpha{list-style-type:lower-alpha}.mw-parser-output .reflist-lower-greek{list-style-type:lower-greek}.mw-parser-output .reflist-lower-roman{list-style-type:lower-roman}
/* end https://en.wikipedia.org/ */
</style><div class="reflist">
<div class="mw-references-wrap"><ol class="references">
<li id="cite_note-1"><span class="mw-cite-backlink"><b><a href="#cite_ref-1">^</a></b></span> <span class="reference-text"><style data-mw-deduplicate="TemplateStyles:r1238218222">
/* start https://en.wikipedia.org/ */
.mw-parser-output cite.citation{font-style:inherit;word-wrap:break-word}.mw-parser-output .citation q{quotes:"\"""\"""'""'"}.mw-parser-output .citation:target{background-color:rgba(0,127,255,0.133)}.mw-parser-output .id-lock-free.id-lock-free a{background:url("./mw/Lock-green.svg")right 0.1em center/9px no-repeat}.mw-parser-output .id-lock-limited.id-lock-limited a,.mw-parser-output .id-lock-registration.id-lock-registration a{background:url("./mw/Lock-gray-alt-2.svg")right 0.1em center/9px no-repeat}.mw-parser-output .id-lock-subscription.id-lock-subscription a{background:url("./mw/Lock-red-alt-2.svg")right 0.1em center/9px no-repeat}.mw-parser-output .cs1-ws-icon a{background:url("./mw/Wikisource-logo.svg")right 0.1em center/12px no-repeat}body:not(.skin-timeless):not(.skin-minerva) .mw-parser-output .id-lock-free a,body:not(.skin-timeless):not(.skin-minerva) .mw-parser-output .id-lock-limited a,body:not(.skin-timeless):not(.skin-minerva) .mw-parser-output .id-lock-registration a,body:not(.skin-timeless):not(.skin-minerva) .mw-parser-output .id-lock-subscription a,body:not(.skin-timeless):not(.skin-minerva) .mw-parser-output .cs1-ws-icon a{background-size:contain;padding:0 1em 0 0}.mw-parser-output .cs1-code{color:inherit;background:inherit;border:none;padding:inherit}.mw-parser-output .cs1-hidden-error{display:none;color:var(--color-error,#d33)}.mw-parser-output .cs1-visible-error{color:var(--color-error,#d33)}.mw-parser-output .cs1-maint{display:none;color:#085;margin-left:0.3em}.mw-parser-output .cs1-kern-left{padding-left:0.2em}.mw-parser-output .cs1-kern-right{padding-right:0.2em}.mw-parser-output .citation .mw-selflink{font-weight:inherit}@media screen{.mw-parser-output .cs1-format{font-size:95%}html.skin-theme-clientpref-night .mw-parser-output .cs1-maint{color:#18911f}}@media screen and (prefers-color-scheme:dark){html.skin-theme-clientpref-os .mw-parser-output .cs1-maint{color:#18911f}}
/* end https://en.wikipedia.org/ */
</style><cite id="CITEREFMeyer" class="citation web cs1">Meyer, Bertrand. <a rel="nofollow" class="external text" href="http://laser.inf.ethz.ch/2012/slides/Meyer/eiffel_laser_2012.pdf">"Eiffel: a language for software engineering"</a> <span class="cs1-format">(PDF)</span>. p. 22<span class="reference-accessdate">. Retrieved <span class="nowrap">16 December</span> 2014</span>.</cite></span>
</li>
<li id="cite_note-2"><span class="mw-cite-backlink"><b><a href="#cite_ref-2">^</a></b></span> <span class="reference-text"><cite id="CITEREFYoung" class="citation web cs1">Young, Greg. <a rel="nofollow" class="external text" href="http://cqrs.files.wordpress.com/2010/11/cqrs_documents.pdf">"CQRS Documents"</a> <span class="cs1-format">(PDF)</span><span class="reference-accessdate">. Retrieved <span class="nowrap">2012-12-28</span></span>.</cite></span>
</li>
<li id="cite_note-FowlerCQRS-3"><span class="mw-cite-backlink">^ <a href="#cite_ref-FowlerCQRS_3-0"><sup><i><b>a</b></i></sup></a> <a href="#cite_ref-FowlerCQRS_3-1"><sup><i><b>b</b></i></sup></a></span> <span class="reference-text"><cite id="CITEREFFowler" class="citation web cs1">Fowler, Martin. <a rel="nofollow" class="external text" href="http://martinfowler.com/bliki/CQRS.html">"CQRS"</a><span class="reference-accessdate">. Retrieved <span class="nowrap">2011-07-14</span></span>.</cite></span>
</li>
<li id="cite_note-4"><span class="mw-cite-backlink"><b><a href="#cite_ref-4">^</a></b></span> <span class="reference-text"><cite id="CITEREFFowler" class="citation web cs1">Fowler, Martin. <a rel="nofollow" class="external text" href="http://martinfowler.com/bliki/CommandQuerySeparation.html">"CommandQuerySeparation"</a><span class="reference-accessdate">. Retrieved <span class="nowrap">5 December</span> 2005</span>.</cite></span>
</li>
</ol></div></div>
<div class="mw-heading mw-heading2"><h2 id="Further_reading">Further reading</h2></div>
<ul><li><cite id="CITEREFMeyer1994" class="citation book cs1"><a href="Bertrand_Meyer" title="Bertrand Meyer">Meyer, Bertrand</a> (September 1994) [1988]. <i>Object-oriented Software Construction</i>. Prentice Hall. <a href="ISBN_(identifier)" class="mw-redirect" title="ISBN (identifier)">ISBN</a> <bdi>0-13-629049-3</bdi>.</cite></li></ul>
<div class="mw-heading mw-heading2"><h2 id="External_links">External links</h2></div>
<ul><li><a rel="nofollow" class="external text" href="http://martinfowler.com/bliki/CommandQuerySeparation.html">Explanation on Martin Fowler's Bliki</a></li></ul></div><!--htdig_noindex--><div><div class="zim-footer">
This article is issued from <a class="external text" title="Last edited on 2024-02-29" href="https://en.wikipedia.org/wiki/?title=Command%E2%80%93query_separation&oldid=1210959838">Wikipedia</a>. The text is available under <a class="external text" href="https://creativecommons.org/licenses/by-sa/4.0/deed.en">Creative Commons Attribution-Share Alike 4.0</a> unless otherwise noted. Additional terms may apply for the media files.
</div>
</div><!--/htdig_noindex--></div>
</div>
</main>
</div>
</div>
</div>
</body></html>